from django.contrib.auth.models import AbstractUser
from django.db import models
import json


class MajorModel(models.Model):
    level_choices = [
        (0, 'A'),
        (1, 'B'),
        (2, 'C'),
        (3, 'D'),
    ]
    name = models.CharField(max_length=100, verbose_name="专业")
    level = models.SmallIntegerField(default=3, choices=level_choices, verbose_name="组别")  # Correct argument
    start = models.IntegerField(verbose_name="start")
    end = models.IntegerField(verbose_name="end")
    num = models.IntegerField(default=0, verbose_name="人数")

    def save(self, *args, **kwargs):
        # 自动计算 num 的值
        self.num = self.end - self.start + 1
        super(MajorModel, self).save(*args, **kwargs)  # 调用父类的 save 方法保存对象

    def __str__(self):
        # 获取 level 对应的标签值
        level_str = dict(self.level_choices).get(self.level, '未知')
        return f"{self.name} - {level_str}"

    class Meta:
        verbose_name = "抽签分类"
        verbose_name_plural = verbose_name

        unique_together = ('name', 'level')


# 专业选择模型
class MajorSelection(models.Model):
    major = models.ForeignKey(MajorModel, on_delete=models.CASCADE)
    num = models.IntegerField(default=0, verbose_name="从当前专业的当前组别抽取的人数")
    user = models.ForeignKey('CustomUser', on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.major.name} - {self.num} 人"

    class Meta:
        verbose_name = "major_selection"
        verbose_name_plural = verbose_name


# 用户模型
class CustomUser(AbstractUser):
    nickname = models.CharField(max_length=225, unique=True, verbose_name='抽签人姓名')
    result_list = models.TextField(blank=True, null=True, default="还未抽签", verbose_name="抽签结果列表")

    def set_result_list(self, color_list):
        self.result_list = json.dumps(color_list)

    def get_result_list(self):
        if self.result_list:
            return json.loads(self.result_list)
        return []

    def __str__(self):
        return self.nickname if self.nickname else "Unnamed User"

    class Meta:
        db_table = 'users'
        verbose_name = "用户"
        verbose_name_plural = verbose_name


class LotteryResultModel(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    major = models.ForeignKey(MajorModel, on_delete=models.CASCADE)
    index_num = models.IntegerField(default=0, verbose_name="编号")

    def __str__(self):
        return f"{self.user.nickname} - - {self.index_num}"

    class Meta:
        verbose_name = '抽签结果'
        verbose_name_plural = verbose_name
